#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#define PATH "."
#define FILENAME "fifo"
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
class NamedFifo
{
public:
    NamedFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoName = _path + "/" + _name;
        int n = mkfifo(_fifoName.c_str(), 0666);
        if (n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "mkfifo create success!" << std::endl;
        }
    }
    ~NamedFifo()
    {
        int n = unlink(_fifoName.c_str());
        if (n < 0)
        {
            ERR_EXIT("unlink");
        }
        else
        {
            std::cout << "unlink success!" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoName;
};

class FileOpt
{
public:
    FileOpt(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoName = _path + "/" + _name;
    }
    // 打开管道
    void OpenForRead()
    {
        _fd = open("fifo", O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open file to read");
        }
        else
        {
            std::cout << "open fifo success" << std::endl;
        }
    }
    void OpenForWrite()
    {
        _fd = open("fifo", O_WRONLY | O_TRUNC);
        if (_fd < 0)
        {
            ERR_EXIT("open file to write");
        }
        else
        {
            std::cout << "open file to write success" << std::endl;
        }
    }
    void Read()
    {
        while (true)
        {
            char buffer[1024];
            int n = read(_fd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "Client say:# " << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "Client has closen,me too!" << std::endl;
                break;
            }
            else
            {
                std::cout << "fifo read failture" << std::endl;
                exit(3);
            }
        }
    }
    void Write()
    {
        int cnt = 1;
        int id = getpid();
        // 写入内容
        while (true)
        {
            std::string msg;
            printf("请输入你想输入的内容: ");
            std::getline(std::cin, msg);
            msg += (", msg number: " + std::to_string(cnt++) + ", [" + std::to_string(id) + "]");
            write(_fd, msg.c_str(), msg.size());
        }
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }
    ~FileOpt()
    {
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoName;
    int _fd;
};
